import React, { useEffect, useState } from "react";
import { Image } from "antd";
import { createStyles } from "antd-style";
import { useRequest } from "ahooks";
import { UndoOutlined } from '@ant-design/icons';

import {ProBox} from "@yaf/pro-ui";
import { globalStore, toApi, prompt } from "@/service";
import useEventSource from "../../hooks/useEventSource";
import { getUserInfo, getWeChatCheckLogin, getWechatLoginInfo } from "../api";

const WeChatLogin: React.FC = () => {
  const { styles } = useStyle();
  const [eventSourceUrl, setEventSourceUrl] = useState("")
  const [isExpire, setIsExpire] = useState(false)

  const { data: weChatLoginResp, loading, run } = useRequest(getWechatLoginInfo)

  const { message, close: eventSourceClose } = useEventSource(eventSourceUrl)

  useEffect(() => {
    let expireTimer = null;

    if (weChatLoginResp?.data) {
      setIsExpire(false)

      setEventSourceUrl(toApi(`events?eventId=${weChatLoginResp?.data?.eventKey}&eventType=login`))

      expireTimer && clearTimeout(expireTimer)
      expireTimer = setTimeout(() => {
        // 二维码失效
        setIsExpire(true)
        // EventSource Close
        eventSourceClose()
      }, weChatLoginResp?.data?.expire_seconds * 1000);
    }

    return () => {
      expireTimer && clearTimeout(expireTimer)
    }
  }, [weChatLoginResp])

  useEffect(() => {
    if (message) {
      const messageData = JSON.parse(message)
      if (messageData?.status === "SUCCESS") {
        getWeChatCheckLogin(messageData?.uuid).then(() => {
          getUserInfo().then(() => {
            prompt.success("登录成功!");
            globalStore.closeLoginModal();

            setTimeout(() => {
              window.location.reload()
            }, 1000)
          })
        })
      }
    }
  }, [message])

  return <div className={styles.weChat}>
    <p>微信扫码关注“闻咖”快速登录</p>

    <div className="qrCode">
      <ProBox loading={loading}>
        <Image src={weChatLoginResp?.data?.url} width="100%" height="100%" preview={false} />
      </ProBox>

      {isExpire && <div
        className="w-full h-full absolute top-0 left-0 bg-[rgba(0,0,0,0.6)] cursor-pointer flex flex-col justify-center items-center"
        onClick={run}
      >
        <UndoOutlined style={{ fontSize: 30, color: "white" }} rotate={90} />
        <span className="text-white">二维码已失效，点击刷新</span>
      </div>}
    </div>

    <a>新注册用户，送您5次作图使用机会</a>
    <span>初始使用时，将通过短信验证码绑定手机号</span>
  </div>
}

export default WeChatLogin;

const useStyle = createStyles(({ css }) => ({
  weChat: css`
    width: 100%;
    text-align: center;
    /* margin-top: 40px; */

    & > p{
      margin: 0;
      font-size: 16px;
      color: #0000004d;
      margin-bottom: 15px;
    }

    .qrCode{
      width: 254px;
      height: 254px;
      margin: 0 auto 15px;
      position: relative;
    }

    & > a{
      display: block;
      font-size: 16px;
      color: #3a7df9;
      margin-bottom: 15px;
      cursor: text;
    }

    & > span{
      font-size: 14px;
      color: #0000004d;
    }
  `
}))
